package cn.varin.mqttclientapi.config;

import cn.varin.mqttclientapi.entity.MqttConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttOutboundConfig {
    @Autowired
    private MqttConfigProperties mqttConfigProperties;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;

    // 建立出站通道
    @Bean
    public MessageChannel messageOutboundChannel(){
        return new DirectChannel();
    }
    // 建立发送消息配置

    @ServiceActivator(inputChannel = "messageOutboundChannel")
    @Bean
    public MessageHandler messageOutboundHandle(){
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
        mqttConfigProperties.getUrl(),
        mqttConfigProperties.getPubClientId(),
        mqttPahoClientFactory
        );
        messageHandler.setDefaultQos(2);
        messageHandler.setDefaultTopic("default");
        messageHandler.setAsync(true);
        return messageHandler;

    }
}
